<template>
  <div class="rain-field-group" >
    <div class="rain-field-cell" >
      <div class="rain-cell-title" >
        <span>{{msg}}</span>
      </div>
      <div class="rain-cell-content" >
        <input
          :name="name"
          :type="type"
          :checkRule="checkRule"
          :mold="mold"
          :maxlength="maxlength"
          :errorMsg="errorMsg+msg"
          :placeholder="placeholder"
          :readonly='isReadonly'
          v-model="currentValue"
          @blur="watchBlur()"
          @input="handleInput"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from "vue-property-decorator"
import Regular from "./regular"
import VerfiyRule from "./verfiyRule"

@Component({
  components: {}
})
export default class Home extends Vue {
  // props
  @Prop(String) msg!:string           //提示信息
  @Prop(String) name!:string          //input-name
  @Prop(String) type!:string          //输入类型
  @Prop(String) value!:string         //input值
  @Prop(String) checkRule!:string     //校验规则
  @Prop(Boolean) isCheckRule!:false   //是否开启校验
  @Prop(String) mold!:string          //input,select
  @Prop(String) maxlength!:number     //最大输入长度
  @Prop(String) placeholder!:string   //展示信息
  //data
  currentValue = this.value
  errorMsg = '请填写正确的'
  isReadonly = false

  // watch
  @Watch('currentValue')
  getCurrentValue(val:any) {
    const len = val.length
    if(len>this.maxlength){
     this.currentValue = this.currentValue.substr(0,this.maxlength)
    }
  }
  // methods
  handleInput(event:any) {
    const value = event.target.value;
    this.$emit('input', value); //触发 input 事件，并传入新值
  }
  watchBlur(){
    if(this.isCheckRule == false){
      return false
    }
    //遍历检查form数据
    const Regulars:any = Regular
    const arr = [{name:this.name,checkRule:Regulars[this.checkRule],value:this.currentValue,msg:this.msg,errorMsg:this.errorMsg}]
    VerfiyRule.verfiyMethod(arr).then((res)=>{
      console.log(res)
    }).catch((err)=>{
      console.error(err)
    })
  }
  watchMold(){
    if(this.mold == 'select'){
      this.isReadonly = true
      this.errorMsg = '请选择'
    }
  }
  // mounted
  mounted() {
    this.watchMold()
  }
}
</script>
<style lang="scss" scoped>
@import "../scss/field.scss";
</style>